'use client'

import { useState } from 'react'
import { Wand2, Image, Loader2, AlertCircle, CheckCircle } from 'lucide-react'

interface IllustrationResult {
  imageUrl: string
  source: string
  prompt: string
  theme: string
  ageGroup: string
  illustrationType: string
  timestamp: string
}

export default function TestOpenAIPage() {
  const [isGenerating, setIsGenerating] = useState(false)
  const [result, setResult] = useState<IllustrationResult | null>(null)
  const [error, setError] = useState<string | null>(null)

  // 测试参数
  const testParams = {
    theme: 'friendship',
    ageGroup: '6-8',
    storyContent: '从前有一只小兔子，它非常喜欢交朋友。有一天，它在森林里遇到了一只受伤的小鸟。小兔子立刻跑过去帮助小鸟，给它找来食物和水。小鸟很快就康复了，它们成为了最好的朋友。',
    illustrationType: 'main' as const,
    useOpenAI: true
  }

  // 测试OpenAI插图生成
  const handleTestOpenAI = async () => {
    setIsGenerating(true)
    setError(null)
    setResult(null)

    try {
      const response = await fetch('/api/generate-illustration', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(testParams),
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || '生成插图失败')
      }

      const data = await response.json()
      setResult(data)
    } catch (error) {
      console.error('测试OpenAI插图生成失败:', error)
      setError(error instanceof Error ? error.message : '未知错误')
    } finally {
      setIsGenerating(false)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-purple-50 py-8">
      <div className="max-w-4xl mx-auto px-4">
        {/* 页面标题 */}
        <div className="text-center mb-8">
          <div className="flex items-center justify-center space-x-3 mb-4">
            <div className="p-3 bg-blue-100 rounded-full">
              <Wand2 className="h-8 w-8 text-blue-600" />
            </div>
            <h1 className="text-3xl font-bold text-gray-900">
              OpenAI插图生成测试
            </h1>
          </div>
          <p className="text-gray-600 max-w-2xl mx-auto">
            测试OpenAI DALL-E 3插图生成功能，验证API配置和图片生成质量
          </p>
        </div>

        {/* 测试控制面板 */}
        <div className="bg-white rounded-xl shadow-lg p-6 mb-8">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-semibold text-gray-900">测试控制</h2>
            <button
              onClick={handleTestOpenAI}
              disabled={isGenerating}
              className="btn-primary flex items-center space-x-2"
            >
              {isGenerating ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Image className="h-4 w-4" />
              )}
              <span>
                {isGenerating ? '生成中...' : '测试OpenAI插图生成'}
              </span>
            </button>
          </div>

          {/* 测试参数显示 */}
          <div className="grid md:grid-cols-2 gap-4 text-sm">
            <div>
              <span className="font-medium text-gray-700">主题：</span>
              <span className="text-gray-600">友谊与分享</span>
            </div>
            <div>
              <span className="font-medium text-gray-700">年龄组：</span>
              <span className="text-gray-600">6-8岁</span>
            </div>
            <div>
              <span className="font-medium text-gray-700">插图类型：</span>
              <span className="text-gray-600">主插图（水彩风格）</span>
            </div>
            <div>
              <span className="font-medium text-gray-700">故事内容：</span>
              <span className="text-gray-600">小兔子帮助受伤小鸟的友谊故事</span>
            </div>
          </div>
        </div>

        {/* 错误显示 */}
        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-8">
            <div className="flex items-center space-x-2">
              <AlertCircle className="h-5 w-5 text-red-500" />
              <h3 className="font-medium text-red-800">测试失败</h3>
            </div>
            <p className="text-red-700 mt-2">{error}</p>
            <div className="mt-3 text-sm text-red-600">
              <p>可能的原因：</p>
              <ul className="list-disc list-inside mt-1 space-y-1">
                <li>OpenAI API密钥未配置或无效</li>
                <li>网络连接问题</li>
                <li>API配额已用完</li>
                <li>服务器错误</li>
              </ul>
            </div>
          </div>
        )}

        {/* 结果显示 */}
        {result && (
          <div className="bg-white rounded-xl shadow-lg p-6">
            <div className="flex items-center space-x-2 mb-4">
              <CheckCircle className="h-5 w-5 text-green-500" />
              <h2 className="text-xl font-semibold text-gray-900">测试成功</h2>
            </div>

            {/* 生成的图片 */}
            <div className="mb-6">
              <h3 className="font-medium text-gray-900 mb-3">生成的插图</h3>
              <div className="relative">
                <img
                  src={result.imageUrl}
                  alt="AI生成的插图"
                  className="w-full max-w-md mx-auto rounded-lg shadow-md"
                />
                <div className="absolute top-2 right-2 bg-black bg-opacity-50 text-white text-xs px-2 py-1 rounded">
                  {result.source === 'openai' ? 'OpenAI DALL-E 3' : '备用图片'}
                </div>
              </div>
            </div>

            {/* 详细信息 */}
            <div className="grid md:grid-cols-2 gap-6">
              <div>
                <h3 className="font-medium text-gray-900 mb-3">生成信息</h3>
                <div className="space-y-2 text-sm">
                  <div>
                    <span className="font-medium text-gray-700">生成服务：</span>
                    <span className={`ml-2 px-2 py-1 rounded text-xs ${
                      result.source === 'openai' 
                        ? 'bg-green-100 text-green-800' 
                        : 'bg-yellow-100 text-yellow-800'
                    }`}>
                      {result.source === 'openai' ? 'OpenAI DALL-E 3' : '备用方案'}
                    </span>
                  </div>
                  <div>
                    <span className="font-medium text-gray-700">主题：</span>
                    <span className="text-gray-600">{result.theme}</span>
                  </div>
                  <div>
                    <span className="font-medium text-gray-700">年龄组：</span>
                    <span className="text-gray-600">{result.ageGroup}</span>
                  </div>
                  <div>
                    <span className="font-medium text-gray-700">插图类型：</span>
                    <span className="text-gray-600">{result.illustrationType}</span>
                  </div>
                  <div>
                    <span className="font-medium text-gray-700">生成时间：</span>
                    <span className="text-gray-600">
                      {new Date(result.timestamp).toLocaleString()}
                    </span>
                  </div>
                </div>
              </div>

              <div>
                <h3 className="font-medium text-gray-900 mb-3">使用的提示词</h3>
                <div className="bg-gray-50 rounded-lg p-3">
                  <p className="text-sm text-gray-700 whitespace-pre-wrap">
                    {result.prompt}
                  </p>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 配置说明 */}
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-6 mt-8">
          <h3 className="font-medium text-blue-900 mb-3">配置说明</h3>
          <div className="text-sm text-blue-800 space-y-2">
            <p>
              <strong>OpenAI API密钥：</strong>
              请在项目根目录创建 <code className="bg-blue-100 px-1 rounded">.env.local</code> 文件，
              并添加 <code className="bg-blue-100 px-1 rounded">OPENAI_API_KEY=your-api-key</code>
            </p>
            <p>
              <strong>测试内容：</strong>
              使用友谊主题的儿童故事，测试水彩风格的主插图生成
            </p>
            <p>
              <strong>回退机制：</strong>
              如果OpenAI不可用，系统会自动使用百度文心一格或占位符图片
            </p>
          </div>
        </div>
      </div>
    </div>
  )
} 